package com.example.servlet.quick.start.demo.request;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@WebServlet(urlPatterns = "/requestDemo2")
public class RequestDemo2 extends HttpServlet {

    /**
     * 获取请求行、请求头数据
     * @param req   an {@link HttpServletRequest} object that
     *                  contains the request the client has made
     *                  of the servlet
     *
     * @param resp  an {@link HttpServletResponse} object that
     *                  contains the response the servlet sends
     *                  to the client
     *
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求头名称
        Enumeration<String> headerNames = req.getHeaderNames();
        // 遍历请求头名称并获取其对应的值
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            String value = req.getHeader(name);
            System.out.println(name + "=" + value);
        }

        // 可以根据浏览器版本做相应的兼容操作
        String userAgent = req.getHeader("user-agent");
        if (userAgent.contains("Chrome")) {
            System.out.println("chrome browser ~~~");
        } else if (userAgent.contains("Firefox")) {
            System.out.println("Firefox browser~~~");
        } else {
            System.out.println("other browser~~~");
        }

        // 直接从浏览器请求该 Servlet 时，referer 为 null
        String referer = req.getHeader("referer");
        if (referer.contains("localhost:18080")) {
            System.out.println("正常访问");
        } else {
            // 防盗链
            System.out.println("禁止访问");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
